package com.block.sms.service.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplateInfo;
import com.block.sms.dto.*;
import com.block.sms.service.ISmsSendService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WoLianSmsSendServiceImpl implements ISmsSendService {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public SmsResultDTO sendSms(SmsParamDTO smsParamDTO, SmsTemplateInfo smsTemplate, SmsConfigInfo smsConfigInfo) {

        SmsResultDTO resultDTO = new SmsResultDTO();
        JSONArray paramArr = smsParamDTO.getParamArray();

        HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getSendUrl());

        String username = smsConfigInfo.getAccountNo();

        String content = StrUtil.format(smsTemplate.getTemplateContent(), paramArr.stream().toArray());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sp_id", username);
        paramMap.put("mobile", smsParamDTO.getMobie());
        paramMap.put("content", content);
        paramMap.put("password", smsConfigInfo.getAccountSecret());

        httpRequest.form(paramMap);

        String bodyResult = httpRequest.execute().body();
        log.info("【沃联短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                smsConfigInfo.getSendUrl(), JSON.toJSONString(paramMap), bodyResult);

        JSONObject resultJson = JSON.parseObject(bodyResult);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("msg");
        Long msg_id = resultJson.getLong("msg_id");

        resultDTO.setResult(bodyResult);
        resultDTO.setCode(String.valueOf(code));
        resultDTO.setMessage(message);
        resultDTO.setOutOrderNo(String.valueOf(msg_id));
        if (ObjectUtil.equals(Integer.valueOf("0"), code)) {
            resultDTO.setSuccess(true);
            return resultDTO;
        }
        resultDTO.setMessage(bodyResult);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

    @Override
    public QueryResultDTO querySendResult(QueryParamDTO queryParamDTO, SmsConfigInfo smsConfigInfo) {
        QueryResultDTO queryResultDTO = new QueryResultDTO();
        queryResultDTO.setStatus("SUCCESS");

        return queryResultDTO;
    }
}
